package lab03.test01.test03;

import java.io.*;

public class Test03 {
    public static void main(String[] args) {
        //通过字节输出流向文件中写入“Beijing欢迎你！

        //1.指明目标文件的路径
        File file = new File("D://test.txt");

        //2.创建字节流输出对象

        byte[] b = "Beijing欢迎你！".getBytes();
        try {
            FileOutputStream outputStream = new FileOutputStream(file);
            outputStream.write(b);
            outputStream.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //通过字节输入流读出文件中的内容并显示
        try {

            //创建字节输入流对象，并与目标文件相接
            FileInputStream fileInputStream = new FileInputStream(file);

          /*
         * 如果读到最后没有数据。则返回-1
         * int read() 读取一个字节，并返回读取的字节
         * int read(byte[] b) 读取多个字节，并存储到数组b中，从数组b的索引为0的地方开始存储，返回读取了几个字节
         * int read(byte[] b,int off,int len)读取len个字节，从数组b的索引为off的地方开始存储
         */
            int i = -1;
            while ((i = fileInputStream.read(b))!=-1){
                String string = new String(b,0,i);
                System.out.println(string);
            }

            fileInputStream.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //在已有文件中再追加“我的学号是：你自己的学号”
        byte[] b1 = "我的学号是：1606101071".getBytes();
        try {

            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(b1);
            fileOutputStream.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            int i = -1;

            while ((i = fileInputStream.read(b))!=-1){
                String string = new String(b,0,i);
                System.out.println(string);
            }

            fileInputStream.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
